// import React from 'react';
// import { Table, Input, Button, Form, Icon } from 'antd';

// const EditableContext = React.createContext();

// const EditableRow = ({ form, index, ...props }) => (
//     <EditableContext.Provider value={form}>
//         <tr {...props} />
//     </EditableContext.Provider>
// );

// const EditableFormRow = Form.create()(EditableRow);

// function EditableCell(props) {
//     const { editable, dataIndex, title, record, index, handleSave, children, ...restProps } = props;
//     const [editing, setEditing] = React.useState(false);
//     const [form, setForm] = React.useState();
//     const inputRef = React.useRef();

//     const toggleEdit = () => {
//         setEditing(!editing);
//     };

//     React.useEffect(() => {
//         if (editing) {
//             inputRef.current.focus();
//         }
//     }, [editing]);

//     const save = e => {
//         form.validateFields((error, values) => {
//             if (error && error[e.currentTarget.id]) {
//                 return;
//             }
//             toggleEdit();
//             handleSave({ ...record, ...values });
//         });
//     };

//     const renderCell = _form => {
//         setForm(_form);
//         return editing ? (
//             <Form.Item style={{ margin: 0 }}>
//                 {form.getFieldDecorator(dataIndex, {
//                     rules: [
//                         {
//                             required: true,
//                             message: `${title} is required.`
//                         }
//                     ],
//                     initialValue: record[dataIndex]
//                 })(<Input ref={inputRef} onPressEnter={save} onBlur={save} />)}
//             </Form.Item>
//         ) : (
//             <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
//                 {children}
//             </div>
//         );
//     };

//     return (
//         <td {...restProps}>
//             {editable ? <EditableContext.Consumer>{renderCell}</EditableContext.Consumer> : children}
//         </td>
//     );
// }

// function EditableTable() {
//     const [dataSource, setDataSource] = React.useState([
//         {
//             key: '0',
//             name: 'Edward King 0',
//             age: '32',
//             address: 'London, Park Lane no. 0'
//         },
//         {
//             key: '1',
//             name: 'Edward King 1',
//             age: '32',
//             address: 'London, Park Lane no. 1'
//         }
//     ]);

//     const [count, setCount] = React.useState(2);

//     const handleDelete = key => {
//         setDataSource(dataSource.filter(item => item.key !== key));
//     };

//     const columns = [
//         {
//             title: '2020年Q4绩效目标',
//             dataIndex: 'name',
//             width: '30%',
//             editable: true
//         },
//         {
//             title: '衡量标准/关键结果',
//             dataIndex: 'age',
//             editable: true
//         },
//         {
//             title: '权重',
//             dataIndex: 'address',
//             editable: true
//         },
//         {
//             title: '操作',
//             dataIndex: 'operation',
//             render: (text, record) =>
//                 dataSource.length >= 1 ? <a onClick={() => handleDelete(record.key)}>删除</a> : null
//         }
//     ];

//     const handleAdd = () => {
//         const newData = {
//             key: count,
//             name: `Edward King ${count}`,
//             age: 32,
//             address: `London, Park Lane no. ${count}`
//         };
//         setDataSource([...dataSource, newData]);
//         setCount(count + 1);
//     };

//     const handleSave = row => {
//         const newData = [...dataSource];
//         const index = newData.findIndex(item => row.key === item.key);
//         const item = newData[index];
//         newData.splice(index, 1, {
//             ...item,
//             ...row
//         });
//         setDataSource(newData);
//     };

//     const components = {
//         body: {
//             row: EditableFormRow,
//             cell: EditableCell
//         }
//     };

//     const finalColumns = columns.map(col => {
//         if (!col.editable) {
//             return col;
//         }
//         return {
//             ...col,
//             onCell: record => ({
//                 record,
//                 editable: col.editable,
//                 dataIndex: col.dataIndex,
//                 title: col.title,
//                 handleSave
//             })
//         };
//     });

//     return (
//         <div>
//             <Table components={components} dataSource={dataSource} columns={finalColumns} pagination={false} />
//             <Button block onClick={handleAdd} style={{ marginTop: 16 }}>
//                 <Icon type="plus" />
//                 新增
//             </Button>
//         </div>
//     );
// }

// export default EditableTable;

import React from 'react';
import { Table, Input, Form, Button } from 'antd';
import { Icon } from '@/pages/Recruitment/components';

const data = [];
for (let i = 0; i < 10; i++) {
    data.push({
        key: i.toString(),
        name: `Edrward ${i}`,
        age: 32,
        address: `London Park no. ${i}`
    });
}
const EditableContext = React.createContext();

function EditableCell(props) {
    const { editing, dataIndex, title, inputType, record, index, children, ...restProps } = props;

    const renderCell = ({ getFieldDecorator }) => (
        <td {...restProps}>
            {editing ? (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(dataIndex, {
                        rules: [
                            {
                                required: true,
                                message: `Please Input ${title}!`
                            }
                        ],
                        initialValue: record[dataIndex]
                    })(<Input />)}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
}

function EditableTable(props) {
    const { form: formProps } = props;
    const [editingKey, setEditingKey] = React.useState('');
    const [dataSource, setDataSource] = React.useState(data);
    const isEditing = record => record.key === editingKey;

    const cancel = () => {
        setEditingKey('');
    };

    const save = (form, key) => {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            const newData = [...data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row
                });
                setDataSource(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setDataSource(newData);
                setEditingKey('');
            }
        });
    };

    const edit = key => {
        setEditingKey(key);
    };

    const columns = [
        {
            title: 'name',
            dataIndex: 'name',
            width: '25%',
            editable: true
        },
        {
            title: 'age',
            dataIndex: 'age',
            width: '15%',
            editable: true
        },
        {
            title: 'address',
            dataIndex: 'address',
            width: '40%',
            editable: true
        },
        {
            title: 'operation',
            dataIndex: 'operation',
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <EditableContext.Consumer>
                            {form => (
                                <Icon
                                    title="确认"
                                    type="confirm_o"
                                    onClick={() => save(form, record.key)}
                                    style={{ marginRight: 8 }}
                                />
                            )}
                        </EditableContext.Consumer>
                        <Icon title="取消" type="cancel_o" onClick={() => cancel(record.key)} />
                    </div>
                ) : (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            disabled={editingKey !== ''}
                            onClick={() => edit(record.key)}
                            style={{ marginRight: 8 }}
                        />
                        <Icon
                            title="删除"
                            type="listfunction_delete_icon_default"
                            onClick={() => {
                                setDataSource(dataSource.filter(item => item.key !== record.key));
                            }}
                        />
                    </div>
                );
            }
        }
    ];

    const components = {
        body: {
            cell: EditableCell
        }
    };

    const finalColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });

    const handleAdd = () => {
        const count = dataSource.length + 1;
        const newData = {
            key: count,
            name: `Edward King ${count}`,
            age: 32,
            address: `London, Park Lane no. ${count}`
        };
        setDataSource([...dataSource, newData]);
    };

    return (
        <EditableContext.Provider value={formProps}>
            <Table components={components} bordered dataSource={dataSource} columns={finalColumns} pagination={false} />
            <Button block type="dashed" style={{ marginTop: 16 }} onClick={handleAdd}>
                + 新增
            </Button>
        </EditableContext.Provider>
    );
}

export default Form.create()(EditableTable);
